<template>
  <div>
    <el-card class="box-card">
      <template #header>
        <div class="clearfix">
          <span>
            <el-breadcrumb separator-class="el-icon-arrow-right">
              <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
              <el-breadcrumb-item>新闻管理</el-breadcrumb-item>
            </el-breadcrumb></span
          >
        </div>
      </template>
      <div>
        <el-button
          type="primary"
          size="small"
          @click="
            editDialogVisible = true;
            eventType = 'add';
          "
          >发布新闻</el-button
        >
        <el-button type="danger" size="small" @click="batchDelete"
          >批量删除</el-button
        >
        <el-select
          v-model="new_type"
          size="small"
          style="width: 150px; margin-left: 15px"
          clearable
          @clear="new_type = ''"
          placeholder="请选择新闻类型"
        >
          <el-option
            v-for="item in newTypes"
            :label="item"
            :value="item"
            :key="item"
          ></el-option>
        </el-select>
        <el-input
          placeholder="请输入内容"
          prefix-icon="el-icon-search"
          v-model="search_key"
          size="small"
          style="width: 250px; margin-left: 15px"
        >
        </el-input>
      </div>
      <el-table
        ref="multipleTable"
        :data="news"
        tooltip-effect="dark"
        v-loading="loading"
        :stripe="true"
        :height="maxHeight"
        style="width: 100%; top: 15px"
        @selection-change="accountSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>

        <el-table-column label="标题" show-overflow-tooltip fixed="left">
          <template #default="scope"
            ><el-link
              type="primary"
              target="_blank"
              v-if="scope.row.url"
              :href="scope.row.url"
              >{{ scope.row.title }}</el-link
            >
            <span v-else>{{ scope.row.title }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="cover" label="封面">
          <template #default="scope">
            <el-image
              style="width: 70%"
              :src="scope.row.image_url"
              fit="scale-down"
              :preview-src-list="[scope.row.image_url]"
            >
            </el-image>
          </template>
        </el-table-column>
        <el-table-column
          prop="username"
          label="创建者"
          width="100"
        ></el-table-column>
        <el-table-column
          prop="new_type"
          label="新闻类型"
          width="100"
        ></el-table-column>
        <el-table-column
          prop="body"
          label="摘要"
          width="300"
          :formatter="stateFormat"
        ></el-table-column>
        <el-table-column
          prop="created"
          label="发布时间"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column prop="updated" label="最近更新" show-overflow-tooltip>
        </el-table-column>

        <el-table-column label="操作" fixed="right" width="180">
          <template #default="scope">
            <el-button
              type="text"
              @click="listComments(scope.row.id, scope.row.title)"
              >查看评论</el-button
            >
            <el-button type="text" @click="userEdit(scope.row)">编辑</el-button>
            <el-popconfirm
              confirmButtonText="确定"
              cancelButtonText="取消"
              icon="el-icon-info"
              cancelButtonType="danger"
              iconColor="red"
              title="确定删除该账号信息吗？"
              @confirm="handleDelete(scope.row.id)"
            >
              <template #reference>
                <span class="delte"
                  ><el-button type="text">删除</el-button></span
                >
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 30px">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-size="15"
          layout="total, prev, pager, next, jumper"
          :total="total"
          :disabled="loading"
        >
        </el-pagination>
      </div>
    </el-card>
  </div>
  <div class="newinfo">
    <el-dialog
      :title="`编辑新闻`"
      v-model="editDialogVisible"
      width="1200px"
      :before-close="editHandleClose"
    >
      <el-form ref="boomRef" :inline="true" :model="newinfo" label-width="80px">
        <el-col :span="12">
          <el-form-item label="新闻类型">
            <el-select
              style="width: 450px"
              v-model="newinfo.new_type"
              placeholder="请选择新闻类型"
            >
              <el-option
                v-for="item in newTypes"
                :label="item"
                :value="item"
                :key="item"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="新闻标题">
            <el-input style="width: 450px" v-model="newinfo.title"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="封面链接">
            <el-input
              style="width: 450px"
              v-model="newinfo.image_url"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-form-item label="链接地址">
          <el-input style="width: 450px" v-model="newinfo.url"></el-input>
        </el-form-item>

        <el-form-item label="新闻摘要">
          <el-input
            type="textarea"
            style="width: 990px"
            rows="6"
            v-model="newinfo.body"
          ></el-input>
        </el-form-item>
      </el-form>
      <editor
        api-key="no-api-key"
        class="editor"
        v-model="newinfo.content"
        :init="{
          height: 400,
          menubar: false,
          language_url: '/tinymce/langs/zh_CN.js', // 语言包的路径
          language: 'zh_CN', //语言
          skin_url: '/tinymce/skins/ui/oxide', // skin路径
          codesample_languages: [
            { text: 'HTML/XML', value: 'markup' },
            { text: 'JavaScript', value: 'javascript' },
            { text: 'CSS', value: 'css' },
            { text: 'PHP', value: 'php' },
            { text: 'Ruby', value: 'ruby' },
            { text: 'Python', value: 'python' },
            { text: 'Java', value: 'java' },
            { text: 'C', value: 'c' },
            { text: 'C#', value: 'csharp' },
            { text: 'C++', value: 'cpp' },
            { text: 'GO', value: 'golang' },
          ],
          plugins: ['lists table wordcount code image codesample'],
          toolbar1:
            'undo redo | codesample | code | fontsizeselect | fontselect | styleselect | bold italic underline | bullist numlist outdent indent | uploadimg table',
          toolbar2:
            'alignleft aligncenter alignright alignjustify | forecolor backcolor | removeformat | link image',
        }"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editHandleClose">取 消</el-button>
          <el-button type="primary" :loading="saveLoading" @click="save"
            >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>

  <div class="comment">
    <el-drawer
      :title="`${newTitle} 共计 ${commentTotal} 条评论`"
      v-model="drawer"
      :size="500"
      :before-close="drawerHandleClose"
    >
      <div>
        <el-empty
          style="margin-left: -80px"
          v-if="commentTotal == 0"
          description="暂无评论"
        ></el-empty>

        <el-timeline v-else v-loading="loadMoreLoading">
          <el-timeline-item
            v-for="item in comments"
            :key="item.id"
            color="#0bbd87"
            :timestamp="item.created"
            ><el-card class="box-card">
              <template #header>
                <div class="card-header">
                  <h4>{{ item.username }}</h4>
                  <el-popconfirm
                    v-if="
                      userInfo.id === item.user_id ||
                      userInfo.user_type === 0 ||
                      userInfo.user_type === 1
                    "
                    confirmButtonText="确定"
                    cancelButtonText="取消"
                    icon="el-icon-info"
                    cancelButtonType="danger"
                    iconColor="red"
                    title="该操作将永久删除评论！"
                    @confirm="handleDeleteComment(item.id)"
                  >
                    <template #reference>
                      <el-button type="text">删除</el-button>
                    </template>
                  </el-popconfirm>
                </div>
              </template>
              {{ item.content }}
            </el-card>
          </el-timeline-item>
        </el-timeline>
        <el-button
          class="loadmore"
          :loading="loadMoreLoading"
          type="success"
          @click="loadMore"
          v-if="commentTotal !== comments.length"
          >加载更多</el-button
        >
      </div>
    </el-drawer>
  </div>
</template>

<script lang="ts">
import TinymceEditor from "@/components/tinymce/index.vue";
import { NewsService } from "@/api/news";
import { UserService } from "@/api/user";
import { reactive, toRefs, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import tinymce from "tinymce/tinymce";
import Editor from "@tinymce/tinymce-vue";
import "tinymce/themes/silver/theme";
import "tinymce/plugins/image";
import "tinymce/plugins/table";
import "tinymce/plugins/lists";
import "tinymce/plugins/wordcount";
import "tinymce/plugins/colorpicker";
import "tinymce/plugins/code";
import "tinymce/plugins/paste";
import "tinymce/plugins/codesample";
import "tinymce/icons/default/icons";

export default {
  name: "AdaminNews",
  components: { TinymceEditor, Editor },
  setup() {
    const handleCurrentChange = (page: number) => {
      data.page = page;
    };
    tinymce.init({});
    const list = () => {
      data.loading = true;
      NewsService.list({
        page: data.page,
        new_type: data.new_type,
        search_key: data.search_key,
      }).then((res) => {
        data.loading = false;
        data.total = res.data.data.total;
        data.news = res.data.data.news;
      });
    };
    const handleDelete = (id: number) => {
      NewsService.delete([id]).then((res) => {
        if (res.data.code === 0) {
          ElMessage.success("删除成功");
          list();
        } else {
          ElMessage.error(res.data.message);
        }
      });
    };
    const userEdit = (news: any) => {
      const { title, content, image_url, id, new_type, url } = news;
      data.newinfo.id = id;
      data.newinfo.content = content;
      data.newinfo.title = title;
      data.newinfo.image_url = image_url;
      data.newinfo.new_type = new_type;
      data.newinfo.url = url;
      data.editDialogVisible = true;
      data.newinfo.body = news.body;
      data.eventType = "edit";
    };
    const batchDelete = () => {
      ElMessageBox.confirm("此操作将永久删除选择的新闻, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "error",
      })
        .then(() => {
          NewsService.delete(data.select_ids).then((res) => {
            if (res.data.code === 0) {
              list();
              ElMessage({
                type: "success",
                message: "删除成功!",
              });
            } else {
              ElMessage({
                type: "error",
                message: res.data.message,
              });
            }
          });
        })
        .catch(() => {});
    };
    const accountSelectionChange = (rows: any) => {
      data.select_ids = [];
      rows.forEach((i: any) => {
        // @ts-ignore
        data.select_ids.push(i.id);
      });
    };
    const initNew = {
      title: "",
      content: "",
      image_url: "",
      id: null,
      new_type: "",
      url: "",
      body: "",
    };
    const editHandleClose = () => {
      data.editDialogVisible = false;
      data.newinfo = { ...initNew };
    };
    const change = (status: number) => {
      // @ts-ignore
      data.status = status;
    };

    const save = () => {
      if (data.newinfo.title === "") {
        ElMessage.error("请输入标题！");
        return;
      }
      if (data.newinfo.body === "") {
        ElMessage.error("请填写新闻摘要！");
        return;
      }
      if (data.newinfo.content === "") {
        ElMessage.error("请填写新闻类容！");
        return;
      }
      data.saveLoading = true;
      if (data.eventType === "edit") {
        NewsService.update({
          id: data.newinfo.id,
          new_type: data.newinfo.new_type,
          title: data.newinfo.title,
          url: data.newinfo.url,
          content: data.newinfo.content,
          image_url: data.newinfo.image_url,
          body: data.newinfo.body,
        }).then((res) => {
          if (res.data.code === 0) {
            list();
            ElMessage.success("修改成功");
          } else {
            ElMessage.error(res.data.message);
          }
          data.newinfo = { ...initNew };
          data.editDialogVisible = false;
          data.saveLoading = false;
        });
      } else {
        NewsService.insert({
          new_type: data.newinfo.new_type,
          title: data.newinfo.title,
          url: data.newinfo.url,
          content: data.newinfo.content,
          image_url: data.newinfo.image_url,
          body: data.newinfo.body,
        }).then((res) => {
          if (res.data.code === 0) {
            list();
            ElMessage.success("发布成功");
          } else {
            ElMessage.error(res.data.message);
          }
          data.newinfo = { ...initNew };
          data.editDialogVisible = false;
          data.saveLoading = false;
        });
      }
    };
    const commentsApi = (replase = true, id = null) => {
      data.loadMoreLoading = true;
      NewsService.commentList({
        page: data.commentPage,
        id: data.commentId,
      }).then((res) => {
        if (res.data.code === 0) {
          data.commentTotal = res.data.data.total;
          if (replase) {
            // @ts-ignore
            data.comments = [...data.comments, ...res.data.data.comments];
          } else {
            data.comments = data.comments.filter((item) => {
              // @ts-ignore
              return item.id != id;
            });
          }
        }
        data.loadMoreLoading = false;
      });
    };
    const listComments = (id: number, title: string) => {
      data.drawer = true;
      // @ts-ignore
      data.commentId = id;
      data.newTitle = title;
      commentsApi();
    };
    const loadMore = () => {
      if (data.commentTotal == data.comments.length) {
        ElMessage.warning("已全部加载");
        return;
      }
      data.loadMoreLoading = true;
      data.commentPage += 1;
      commentsApi();
    };
    const handleDeleteComment = (id: number) => {
      NewsService.deleteComment(id).then((res) => {
        if (res.data.code === 0) {
          // @ts-ignore
          commentsApi(false, id);
        } else {
          ElMessage.error(res.data.message);
        }
      });
    };
    const drawerHandleClose = () => {
      data.drawer = false;
      data.commentTotal = 0;
      data.commentId = null;
      data.newTitle = "";
      data.commentPage = 1;
      data.comments = [];
    };
    let data = reactive({
      maxHeight: document.documentElement.clientHeight - 280,
      search_key: "",
      loadMore: loadMore,
      page: 1,
      news: [],
      newinfo: { ...initNew },
      total: 0,
      select_ids: [],
      userInfo: {},
      eventType: "add",
      commentPage: 1,
      commentTotal: 0,
      commentId: null,
      newTitle: "",
      comments: [],
      loadMoreLoading: false,
      new_type: "",
      loading: false,
      drawer: false,
      handleDeleteComment: handleDeleteComment,
      handleCurrentChange: handleCurrentChange,
      handleDelete: handleDelete,
      userEdit: userEdit,
      batchDelete: batchDelete,
      accountSelectionChange: accountSelectionChange,
      editDialogVisible: false,
      saveLoading: false,
      editHandleClose: editHandleClose,
      change: change,
      save: save,
      listComments: listComments,
      drawerHandleClose: drawerHandleClose,
      newTypes: [
        "军事",
        "娱乐",
        "国际",
        "国内",
        "财经",
        "体育",
        "互联网",
        "科技",
        "游戏",
        "汽车",
        "房产",
      ],
      // @ts-ignore
      stateFormat(row, column, cellValue) {
        if (!cellValue) return "";
        if (cellValue.length > 100) {
          //最长固定显示10个字符
          return cellValue.slice(0, 100) + "...";
        }
        return cellValue;
      },
    });
    list();
    watch(
      () => data.search_key,
      (newValue, oldVlaue) => {
        data.page = 1;
        data.search_key = newValue;
        list();
      }
    );
    watch(
      () => data.page,
      (newValue, oldVlaue) => {
        list();
      }
    );
    watch(
      () => data.new_type,
      (newValue, oldVlaue) => {
        list();
      }
    );
    const getHeight = () => {
      data.maxHeight = document.documentElement.clientHeight - 280;
    };
    window.addEventListener("resize", getHeight, false);
    UserService.info().then((res) => {
      if (res.data.code === 0) {
        data.userInfo = res.data.data;
      }
    });
    return {
      ...toRefs(data),
    };
  },
};
</script>

<style lang="less">
.delte {
  .el-button--text {
    color: red !important;
    margin-left: 10px;
  }
}

.newinfo {
  .el-dialog {
    margin-top: 5vh !important;
  }
  .el-dialog__body {
    padding: 20px 25px !important;
  }
  .el-overlay {
    z-index: 99 !important;
  }
}
.comment {
  .el-drawer__body {
    overflow-y: auto;
    padding-left: 80px !important;
    padding-top: 25px !important;
  }
  .el-timeline-item__content {
    width: 80% !important;
  }
  .loadmore {
    margin-bottom: 30px;
  }
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .el-card__header {
    padding: 0px 20px !important;
  }
  .el-button--text {
    color: red !important;
  }
}
</style>